package com.easy;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created by Lxk on 2019/5/17.
 */
public class Solution637 {

    public List<Double> averageOfLevels(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        List<Double> avgRes = new ArrayList<>();
        if(root == null){
            return avgRes;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode levelEnd = root;
        TreeNode lastNode = root;
        queue.offer(root);
        List<Integer> level = new ArrayList<>();
        while(!queue.isEmpty()){
            TreeNode cur = queue.poll();
            if(cur.left != null){
                queue.offer(cur.left);
                lastNode = cur.left;
            }
            if(cur.right != null){
                queue.offer(cur.right);
                lastNode = cur.right;
            }
            level.add(cur.val);
            if(cur == levelEnd){
                levelEnd = lastNode;
                res.add(level);
                level = new ArrayList<>();
            }
        }
        for(List<Integer> list : res){
            Double sum = new Double(0.0);
            for(Integer val : list){
                sum += val;
            }
            avgRes.add(sum/list.size());
        }

        return avgRes;
    }

}
